package com.example.pets.model.datasource.DataSourceImpl;


import android.content.Context;

import com.example.pets.MapApplication;
import com.example.pets.model.datasource.UserDataSource;
import com.example.pets.model.entities.User;
import com.example.pets.model.entities.dao.UserDao;
import com.example.pets.model.entities.database.AppDatabase;

import java.util.List;


public class UserDataSourceImpl implements UserDataSource {


    private final UserDao userDao;
    private final AppDatabase db;

    public UserDataSourceImpl() {
         db = AppDatabase.getDatabase(MapApplication.mContext);
         userDao = db.userDao();
    }

    @Override
    public void login(String email, String password, AuthCallback callback) {
     new Thread(new Runnable() {
         @Override
         public void run() {
             User muser = null;
             List<User> users = userDao.findByEmail(email);
             if (users != null && users.size() > 0) {
                 for (User s : users) {
                     if (s.getPassword().equals(password)) {
                         callback.onSuccess(s);
                         muser = s;
                     }
                 }
                 if(muser==null){
                     callback.onFailure("密码不正确");
                 }

             } else {
                 callback.onFailure("此账号不存在，请先注册");
             }
         }
     }).start();

    }

    @Override
    public void register(String email, String password, AuthCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                User s=new User(email,password);
                long id = userDao.insert(s);
                if(id>0){
                    callback.onSuccess(s);
                }else {
                    callback.onFailure("注册失败");
                }
            }
        }).start();

    }
}
